// Copyright (c) 2022 NetEase, Inc. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.

import 'package:hawk/hawk.dart';
import 'package:nim_core/nim_core.dart';

import '../main_test.dart';
import 'method_name_value.dart';

class HandleLoginCase extends HandleBaseCase {
  HandleLoginCase();

  @override
  Future<ResultBean?> handle(event) async {
    super.handle(event);

    var isCallback = false;

    if (className?.trim() != 'AuthService') {
      return null;
    }

    var handled = false;
    var result;
    switch (methodName?.trim()) {
      case login:
        Map map = params![0]['loginInfo'];
        result = await NimCore.instance.authService
            .login(NIMLoginInfo.fromMap(Map<String, dynamic>.from(map)));
        handled = true;
        break;
      case logout:
        result = await NimCore.instance.authService.logout();
        handled = true;
        break;
      case 'kickOutOtherOnlineClient':
        result = await NimCore.instance.authService.kickOutOtherOnlineClient(
            NIMOnlineClient.fromMap(params![0]['client']));
        handled = true;
        break;
      case 'authStatus':
        {
          isCallback = true;
          subsriptions
              .add(NimCore.instance.authService.authStatus.listen((event) {
            print('AuthService#authStatus $event');
            IntegratedManager.instance.report('authStatus',
                ResultBean(code: 0, data: {"status": event.status.name}));
          }));
          break;
        }
      case 'onlineClients':
        {
          isCallback = true;
          subsriptions
              .add(NimCore.instance.authService.onlineClients.listen((event) {
            print('AuthService#onlineClients $event');
            IntegratedManager.instance.report(
                'onlineClients',
                ResultBean(
                    code: 0, data: event.map((e) => e.toMap()).toList()));
          }));
          break;
        }
    }

    if (isCallback) {
      handleCaseResult = ResultBean.success(data: null);
    }

    if (handled) {
      print('AuthServiceTest#$methodName result: ${result.code}');
      handleCaseResult = ResultBean(
        code: result.code,
        data: null,
        message: result.errorDetails,
      );
    }
    return handleCaseResult;
  }
}
